#ifndef __TCP_ECHO_SERVER_HPP__
#define __TCP_ECHO_SERVER_HPP__

#include "Comm.hpp"
#include "Logger.hpp"
#include "InetAddr.hpp"
#include "ThreadPool.hpp"

#include <iostream>
#include <string>
#include <cstdlib>
#include <cstring>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/wait.h>
#include <signal.h>
#include <pthread.h>

static const int gdefaultfd = -1;
static const int gbacklog = 8;
static const int gport = 8080;

using task_t = std::function<void()>;

class TcpEchoServer
{
private:
    // 长任务-> sockfd -> 长连接
    // 短任务-> 短连接
    void HandlerIO(int sockfd, InetAddr client)
    {
        char buffer[1024];
        while (true)
        {
            buffer[0] = 0;
            // 约定：你给我发过来的是命令字符串！ls -a -l touch XX
            ssize_t n = read(sockfd, buffer, sizeof(buffer) - 1);
            if (n > 0)
            {
                buffer[n] = 0;
                std::string echo_string = "server echo# ";
                echo_string += buffer;
                LOG(LogLevel::DEBUG) << client.ToString() << "say: " << buffer;
                write(sockfd, echo_string.c_str(), echo_string.size());
            }
            else if (n == 0)
            {
                LOG(LogLevel::INFO) << "client "
                                    << client.ToString() << " quit, me too, close fd: " << sockfd;
                break;
            }
            else
            {
                LOG(LogLevel::WARNING) << "read client "
                                       << client.ToString() << " error, sockfd : " << sockfd;
                break;
            }
        }

        close(sockfd); // 一定要关闭
    }

public:
    TcpEchoServer(uint16_t port = gport)
        : _listensockfd(gdefaultfd), _port(port)
    {
    }
    void Init()
    {
        // 1. create socket fd
        _listensockfd = socket(AF_INET, SOCK_STREAM, 0);
        if (_listensockfd < 0)
        {
            LOG(LogLevel::FATAL) << "create tcp socket error";
            exit(SOCKET_CREATE_ERR);
        }
        LOG(LogLevel::INFO) << "create tcp socket success: " << _listensockfd; // 3

        // 2. bind socket fd
        InetAddr local(_port);

        if (bind(_listensockfd, local.Addr(), local.Length()) != 0)
        {
            LOG(LogLevel::FATAL) << "bind socket error";
            exit(SOCKET_BIND_ERR);
        }
        LOG(LogLevel::INFO) << "bind socket success: " << _listensockfd;

        // 3. set socket listen
        // 一个tcp server，listen，启动之后，服务器已经算是运行了
        if (listen(_listensockfd, gbacklog) != 0)
        {
            LOG(LogLevel::FATAL) << "listen socket error";
            exit(SOCKET_LISTEN_ERR);
        }
        LOG(LogLevel::INFO) << "Listen socket success: " << _listensockfd;
    }

    class ThreadData
    {
    public:
        ThreadData(int sockfd, TcpEchoServer *self, const InetAddr &addr)
        : _sockfd(sockfd), _self(self), _addr(addr)
        {}
    public:
        int _sockfd;
        TcpEchoServer *_self;
        InetAddr _addr;
    };

    static void *Routine(void *args)
    {
        ThreadData *td = static_cast<ThreadData*>(args);
        pthread_detach(pthread_self());
        td->_self->HandlerIO(td->_sockfd, td->_addr);
        delete td;

        return nullptr;
    }
    void Start()
    {
        // signal(SIGCHLD, SIG_IGN); // 最佳实践
        while (true)
        {
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);
            int sockfd = accept(_listensockfd, (struct sockaddr *)&peer, &len);
            if (sockfd < 0)
            {
                LOG(LogLevel::WARNING) << "accept client error";
                continue;
            }
            InetAddr clientaddr(peer);
            LOG(LogLevel::INFO) << "获取新连接成功, sockfd is : " << sockfd
                                << " client addr: " << clientaddr.ToString();
            // 多进程，多线程
            // 1. 效率问题，创建进程线程
            // 2. 执行流个数没有上限

            // 进程池4:
            ThreadPool<task_t>::GetInstance()->Enqueue([this, sockfd, clientaddr](){
                this->HandlerIO(sockfd, clientaddr);
            });

            //version3 多线程做法

            // 多线程是如何看待主线程曾经打开的文件描述符表！共享
            // 主线程和新线程需要关闭历史fd吗？不需要！
            // pthread_t tid;
            // ThreadData *td = new ThreadData(sockfd, this, clientaddr);
            // pthread_create(&tid, nullptr, Routine, (void*)td);

            // handler sockfd
            // version1 -- 单进程的！
            // HandlerIO(sockfd, clientaddr);

            // version2 --- 多进程
            // 创建子进程，子进程是如何看待父进程的fd的？
            // socketfd可以被子进程继承！
            // pid_t id = fork();
            // if (id < 0)
            // {
            //     LOG(LogLevel::FATAL) << "资源不足，创建子进程失败";
            //     exit(FORK_ERR);
            // }
            // else if (id == 0)
            // {
            //     // child -> sockfd -> 也能看到_listensockfd
            //     close(_listensockfd);
            //     if(fork()>0)
            //         exit(OK);

            //     // 孙子进程
            //     HandlerIO(sockfd, clientaddr); // while(true)
            //     exit(OK);
            // }
            // else
            // {
            //     close(sockfd); // 1. 关闭无用fd 2. 规避fd泄漏！
            //     // father -> _listensockfd -> sockfd
            //     pid_t rid = waitpid(id, nullptr, 0);
            //     (void)rid;
            // }
        }
    }
    ~TcpEchoServer()
    {
    }

private:
    int _listensockfd; // 监听socket
    uint16_t _port;
};

#endif